import path from 'path';

import { DriverPath } from './driverPath';
import { GlobalBuses } from '$domain/service/eventBus';
import { DriverManager } from './driverManager';
import { DriverReloadedEvent } from '$domain/event';
import { DRIVER_CONFIG_FILE_NAME } from './constant';
import { ChokidarFileWatcher, logger, WatcherEvent } from '$common';
export class DriverWatcher {

  private static _watcher: ChokidarFileWatcher;

  private static reloadDriversIfNecessary = (filePath: string) => {
    if (path.basename(filePath) === DRIVER_CONFIG_FILE_NAME) {
      logger.info('🔻 Observed changes in drivers folder, reload drivers...');
      DriverManager.Instance.reload();
      GlobalBuses.DriverEvent.publish(DriverReloadedEvent.NAME);
    }
  }

  static start() {
    if (!this._watcher) {
      logger.debug(`👀 Listen for changes(add, modify, delete) of '${DRIVER_CONFIG_FILE_NAME}' files in directory ${DriverPath.driverAssemblyPath} `);
      this._watcher = new ChokidarFileWatcher(DriverPath.driverAssemblyPath);
      this._watcher.on(WatcherEvent.FileAdded, this.reloadDriversIfNecessary);
      this._watcher.on(WatcherEvent.FileChanged, this.reloadDriversIfNecessary);
      this._watcher.on(WatcherEvent.FileRemoved, this.reloadDriversIfNecessary);
      this._watcher.start();
    }
  }
}